package net.magicalcloud.magicalcloud.base;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import butterknife.ButterKnife;

/**
 * activity基类
 * Created by Pei on 2018/6/6.
 */

public abstract class BaseActivity<V,T extends BasePresenter<V>> extends AppCompatActivity {

    protected T mPresenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //创建presenter
        mPresenter= createPresenter();
        //绑定view
        mPresenter.attachView((V)this);
    }


    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        //绑定ButterKnife
        ButterKnife.bind(this);
    }
    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        super.setContentView(view, params);
        //绑定ButterKnife
        ButterKnife.bind(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除绑定presenter
        mPresenter.detachView();
    }

    //创建Presenter
    protected abstract T createPresenter();


    /**
     * 封装启动活动
     * @param target 目标活动
     * @param bundle 数据
     * @param finish 是否销毁当前活动
     */
    public void startActivity(Class<? extends Activity> target, Bundle bundle, boolean finish) {
        Intent intent = new Intent();
        intent.setClass(this, target);
        if (bundle != null)
            intent.putExtra(getPackageName(), bundle);
        startActivity(intent);
        if (finish)
            finish();
    }

    /**
     * 获得传进当前活动的参数
     * @return bundle
     */
    public Bundle getBundle() {
        if (getIntent() != null && getIntent().hasExtra(getPackageName()))
            return getIntent().getBundleExtra(getPackageName());
        else
            return null;
    }

    //线程
    protected void runOnMain(Runnable runnable) {
        runOnUiThread(runnable);
    }

    /**
     * toast封装
     */
    private Toast toast;
    public void toast(final Object obj) {
        try {
            runOnMain(new Runnable() {
                @Override
                public void run() {
                    if (toast == null)
                        toast = Toast.makeText(BaseActivity.this, "",Toast.LENGTH_SHORT);
                    toast.setText(obj.toString());
                    toast.show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
